package com.roadmap.ajax.handler;

import org.apache.log4j.Logger;

import com.roadmap.client.module.IManager;
import com.roadmap.client.module.goal.GoalManager;
import com.roadmap.common.RdcLogger;
import com.roadmap.entities.LifeGoal;

public class GoalHandler {
	private final static Logger logger = RdcLogger.getLogger(GoalHandler.class);
	private IManager goalManager;

	public IManager getGoalManager(String aspirantId) {
		if (goalManager == null) {
			goalManager = new GoalManager(aspirantId);
		}
		return goalManager;
	}

	/** create or update a goal and return its id */
	public LifeGoal saveGoal(LifeGoal goal) {
		if (goal == null || goal.getAspirantId() == null) {
			logger.error("entity or its owner id is NULL.");
			return null;
		}
		try {
			IManager mgr = getGoalManager(goal.getAspirantId());
			if (goal.getId() == null) {
				mgr.create(goal);
			}
			else {
				mgr.edit(goal);
			}
			return goal;
		}
		catch (Exception e) {
			logger.error(e);
		}
		return null;
	}

	public boolean deleteGoal(String aspirantId, String goalId) {
		if (aspirantId == null || goalId == null) {
			logger.error("user id or goal id is NULL.");
			return false;
		}

		IManager mgr = getGoalManager(aspirantId);
		try {
			LifeGoal goal = (LifeGoal) mgr.get(goalId);
			if (goal == null) {
				logger.error("The goal was not found - " + goalId);
				return false;
			}
			mgr.delete(goal);
			return true;
		}
		catch (Exception e) {
			logger.error(e);
		}

		return false;
	}
	
	public LifeGoal complete(String aspirantId, String goalId){
		try{
			LifeGoal goal = (LifeGoal)getGoalManager(aspirantId).get(goalId);
			if(goal != null){
				getGoalManager(aspirantId).complete(goal);
				return goal;
			}
		}
		catch (Exception e){
			
		}
		return null;
	}
	
	public LifeGoal cancel(String aspirantId, String goalId){
		try{
			LifeGoal goal = (LifeGoal)getGoalManager(aspirantId).get(goalId);
			if(goal != null){
				getGoalManager(aspirantId).cancel(goal);
				return goal;
			}
		}
		catch (Exception e){
			
		}
		return null;
	}
}
